package com.distributeredis.redis_springboot.springbootinterceptor.springbootinterceptortest.aop;

import com.distributeredis.redis_springboot.springbootinterceptor.springbootinterceptortest.service.TestDogService;
import com.distributeredis.redis_springboot.springbootinterceptor.springbootinterceptortest.service.impl.TestDogServiceImpl;
import com.distributeredis.redis_springboot.springbootinterceptor.springbootinterceptortest.vo.TestDog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class MyTestAspect {
    @Autowired
    private TestDogServiceImpl testDogService;

    @Pointcut("@annotation(com.distributeredis.redis_springboot.springbootinterceptor.springbootinterceptortest.aop.MyTestAop)")
    public void pt(){}

    @Around("pt()")
    public Object testAround(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs(); // 参数
        // 获取签名
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method methodNames = methodSignature.getMethod();
        String methodName = methodNames.getName();

        // 获取目标类的名称
        String classType = pjp.getTarget().getClass().getName();
        Class<?> aClass = Class.forName(classType);
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method : declaredMethods) {
            if(method.isAnnotationPresent(MyTestAop.class)) {
                // 获取这个注解的属性信息
                MyTestAop annotation = method.getAnnotation(MyTestAop.class);
                // 获取注解上的属性字段内容
                String value = annotation.value();
                boolean toRun = annotation.isToRun();
                System.out.println("value:"+value+"--------"+"toRun:"+toRun);
                System.out.println("args"+ Arrays.toString(args));
                args[0] = new TestDog("李四","10");
            }
        }
        return pjp.proceed(args);
    }
}
